<?php

namespace Framework\Utils;

class XmlHelper
{
    public static $xml;

    public static function convertToXml($content, $encoding = 'utf-8')
    {
        if (is_array($content)) {
            return self::arrayToXml($content);
        }
        /*        self::$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';*/
        self::$xml = '<xml>';
        self::$xml .= '<content>' . $content . '</content>';
        self::$xml .= '</xml>';

        return self::$xml;
    }

    public static function getXml()
    {
        return self::$xml;
    }

    public static function arrayToXml($array)
    {
        self::$xml = '<xml>';
        self::$xml .= self::_array2xml($array);
        self::$xml .= '</xml>';
        return self::$xml;
    }

    protected static function _array2xml($array)
    {
        $xml = '';
        foreach ($array as $key => $val) {
            if (is_numeric($key)) {
                $key = "item id=\"$key\"";
            } else {
                //去掉空格，只取空格之前文字为key
                list($key) = explode(' ', $key);
            }
            $xml .= "<$key>";
            $xml .= is_array($val) ? self::_array2xml($val) : $val;
            //去掉空格，只取空格之前文字为key
            list($key) = explode(' ', $key);
            $xml .= "</$key>";
        }
        return $xml;
    }

    public static function xmlToArray($xml)
    {
        $postObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = self::_xml2arr($postObj);
        return $data;
    }

    protected static function _xml2arr($obj, $l = 1)
    {
        $arr = array();
        foreach ($obj as $key => $value) {
            if (isset($arr[$key])) {
                if (isset($arr[$key][0])) {
                    if ($value->children()) {
                        $arr[$key][] = self::_xml2arr($value, $l++);
                    } else {
                        $arr[$key][] = strval($value);
                    }
                } else {
                    $arr[$key] = array($arr[$key]);
                    if ($value->children()) {
                        $arr[$key][] = self::_xml2arr($value, $l++);
                    } else {
                        $arr[$key][] = strval($value);
                    }
                }
            } else {
                if ($value->children()) {
                    $arr[$key] = self::_xml2arr($value, $l++);
                } else {
                    $arr[$key] = strval($value);
                }
            }
        }
        return $arr;
    }
}
